<template>
  <div id="cube" />
</template>

<script setup>
import { onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import * as THREE from 'three'
import { createMultiMaterialObject } from 'three/examples/jsm/utils/SceneUtils'
import { destroy } from '@/utils'

let scene, camera, renderer, cube, animationID

onMounted(() => {
  init()
})

const init = () => {
  let container = document.getElementById('cube');
  // 创建场景
  scene = new THREE.Scene();
  // 加背景色
  scene.background = new THREE.Color(0x9370DB)
  // 创建相机
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  // 设置照相机的位置
  camera.position.z = 5;
  // 创建渲染器，设置尺寸为窗口尺寸，并将渲染后的元素添加到body
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  // 创建一个Mesh（橘红（OrangeRed）色的3D立方体），并添加到场景中
  // 创建几何体模型（立方几何体）
  // let geometry = new THREE.BoxGeometry();
  // 创建圆环几何体模型
  // 环面半径为2，管道半径为1，管道横截面分段数为16，管道分段数为6
  let geometry = new THREE.TorusGeometry(2, 1, 16, 100);
  // 创建基础网格材质
  let materialBasic = new THREE.MeshBasicMaterial({
    color: 0xFF4500,
    wireframe: true   // 是否将几何体渲染为线框，默认值为false（即渲染为平面多边形）
  });
  // 创建法线网格材质
  let materialNormal = new THREE.MeshNormalMaterial();
  // 创建多种网格（因为有多个材质）
  // 第一个参数是几何模型，第二参数是材质
  cube = createMultiMaterialObject(geometry, [
    materialBasic,
    materialNormal
  ]);
  // cube = new THREE.Mesh(geometry, material);
  scene.add(cube);
  // 为了方便观察3D图像，添加三维坐标系对象
  // let axes = new THREE.AxesHelper(6);
  // scene.add(axes);

  animate();
}


// 浏览器每次渲染的时候更新立方体的旋转角度
const animate = () => {
  animationID = requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  console.log('cube')

  renderer.render(scene, camera);
};

onBeforeUnmount(() => {
  destroy(scene, renderer, animationID)
})

onUnmounted(() => {
  console.log('Cube组件卸载了')
})

</script>

<style scoped>
#cube {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0
}
</style>
